package work.array;

import java.util.Arrays;

/**
 * @author WDH
 * @description
 * @date 2024年12月04日 16:06
 */

public class Problem27 {


    public int removeElement(int[] nums, int val) {
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
            if (nums[fastIndex] != val) {
                nums[slowIndex] = nums[fastIndex];
                slowIndex++;
            }
        }
        System.out.println("After removeElement: " + Arrays.toString(nums));
        return slowIndex;
    }


    public int removeElement2(int[] nums, int val) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            if (nums[left] == val) {
                nums[left] = nums[right];
                right--;
            } else {
                // 这里兼容了right指针指向的值与val相等的情况
                left++;
            }
        }
        System.out.println("After removeElement2: " + Arrays.toString(nums));
        return left;
    }




    public static void main(String[] args) {
        Problem27 problem27 = new Problem27();
        int[] nums = new int[]{1, 2, 3, 2, 3, 4, 1, 2, 3, 3, 2, 3};
        problem27.removeElement(nums, 2);
        problem27.removeElement2(nums, 2);
    }
}
